package com.mh.mh.netty.reconnheart;

import io.netty.bootstrap.Bootstrap;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.timeout.IdleStateHandler;
import io.netty.util.CharsetUtil;

import java.net.InetSocketAddress;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.concurrent.TimeUnit;

/**
 * 客户端启动类
 */
public class AppClientReconnHeart {
    private final String host ;
    private final int port ;

    public AppClientReconnHeart(String host, int port){
        this.host = host;
        this.port = port;
    }


    public void run() throws InterruptedException {
        /**
         * 配置相应的参数，提供连结到远端的方法
         */
        EventLoopGroup group = new NioEventLoopGroup();// IO线程池
        try {
            Bootstrap bs = new Bootstrap();// 客户端辅助启动类
            bs.group(group)
                    .channel(NioSocketChannel.class)// 实例化一个channel
                    .remoteAddress(new InetSocketAddress(host,port))
                    .handler(new ChannelInitializer<SocketChannel>() {// 进行通道初始化配置
                        @Override
                        protected void initChannel(SocketChannel socketChannel) throws Exception {
                            // 超时检测的handler（读超时，写超时，读写超时写0不启用，时间单位）
                            socketChannel.pipeline().addLast(new IdleStateHandler(5,0,0, TimeUnit.SECONDS));
                            // pipeline 是所有handler的容器，会一步步去执行handler
                            socketChannel.pipeline().addLast(new HandlerClientReconnHeart());// 添加自定义的handler
                        }
                    });

            // 连接到远程节点，等待连接完成
//            ChannelFuture future = bs.connect().sync();
            ChannelFuture future = bs.connect(); // 去掉阻塞，从同步阻塞改为了异步阻塞
            future.addListener(new ListenerClientReconnHeart());

            while (true){
                Thread.sleep(6000);
                SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                String strDate = df.format(new Date());
                future.channel().writeAndFlush(Unpooled.copiedBuffer(strDate, CharsetUtil.UTF_8));
            }

        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            group.shutdownGracefully().sync();
        }
    }

    public static void main(String[] args) throws InterruptedException {
        new AppClientReconnHeart("127.0.0.1", 7770).run();
    }


}
